package com.acme.domain.email.impl;

import java.util.LinkedList;
import java.util.List;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;

public class QueueImpl implements Queue {

	private boolean queueClosed = false;
	private boolean returnFlag = false;
	List<Email> mails = new LinkedList<Email>();

	public synchronized void addEmail(Email email) {
		mails.add(email);
		notifyAll();
	}
 
	public synchronized boolean isQueueClosed() {
		return queueClosed;
	}

	public synchronized void setQueueClosed(boolean queueClosed) {
		this.queueClosed = queueClosed;
	}

	public boolean getReturnFlag() {
		return this.returnFlag;
	}

	// Due to our req we need to implement queue using asynchronous thread,
	// which must delete mails, if queue isn't empty. 
	// Task requirement: use wait/notify mechanism.
	public synchronized Email getEmail() {
		while (mails.isEmpty()) {
			try {
				wait();
			} catch (InterruptedException e) {
				returnFlag = true;
				return null;
			}
		}
		while (!(mails.isEmpty())) {
			return mails.remove(0);
		}
		return null;

	}

	public boolean isEmpty() {
		return mails.isEmpty();
	}
}
